package server.simple100;

import org.junit.Test;

/***
 * 234. 回文链表
 */
public class LeetCode234 {


    @Test
    public void test() {
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(2);
        ListNode listNode4 = new ListNode(2);
        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        System.out.println(isPalindrome(listNode1));
    }

    public boolean isPalindrome(ListNode head) {
        StringBuilder sb = new StringBuilder();
        while (head != null) {
            sb.append(head.val);
            head = head.next;
        }
        // System.out.println(sb.toString());
        // 判断长度是奇数还是偶数
        boolean isD = sb.length() % 2 == 0;
        int zIndex = sb.length() / 2;
        // 1221 -> 12
        String l = sb.substring(0, zIndex);
        // 1221 -> 21
        String r = sb.substring(zIndex + (isD ? 0 : 1));
        for (int i = 0; i < l.length(); i++) {
            if (l.charAt(i) != r.charAt(l.length() - i - 1)) {
                return false;
            }
        }
        return true;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
